<script setup lang="ts">
  import { ref, defineEmits, computed, watch, onMounted, nextTick } from 'vue';
  import { useBooleanStore } from '@/store';
  import {
    searchParamsByReturn,
    prtFrtHcxScan,
    prMaterialOut,
    submitReturnSales,
    deleteReturnApplyByIds,
  } from '@/api/material-receipt';
  import { Notification } from '@arco-design/web-vue';

  const emit = defineEmits(['updateArray']);
  const booleanStore = useBooleanStore();
  // 表单查询数据
  const itemCode = ref('');
  const productCode = ref('');
  const batchNo = ref('');
  const startLotNo = ref('');
  const endLotNo = ref('');
  const qualityCode = ref('');
  const returnStatus = ref('');
  const applyEmpCode = ref('');
  const startTime = ref('');
  const endTime = ref('');
  const scanInput = ref<any>('');
  const scanCode = ref<string>('');

  const pageSize = ref<number>(30);
  const pageNumber = ref<number>(1);

  // 物料数据
  const materialList = ref<any[]>([]);
  // 显示物料信息
  const materialCard = ref<boolean>(false);
  // 缓存箱编码
  const prtCode = ref<string>('');

  // 发送搜索数据
  const flowQueryData = ref({
    searchParams: computed(() => ({
      itemCode: itemCode.value,
      productCode: productCode.value,
      batchNo: batchNo.value,
      startLotNo: startLotNo.value,
      endLotNo: endLotNo.value,
      qualityCode: qualityCode.value,
      returnStatus: returnStatus.value,
      applyEmpCode: applyEmpCode.value,
      startTime: startTime.value,
      endTime: endTime.value,
    })),
    pageParameter: computed(() => ({
      rows: pageSize.value,
      page: pageNumber.value,
    })),
  });
  const newData: any = ref<any[]>([]);
  const wmsDeliveryPlanId = ref<string>('');
  // 表格数据
  async function handleSearch() {
    newData.value = await searchParamsByReturn(flowQueryData.value);
    emit('updateArray', newData.value);
  }
  // 重置
  function reset() {
    itemCode.value = '';
    productCode.value = '';
    batchNo.value = '';
    startLotNo.value = '';
    endLotNo.value = '';
    qualityCode.value = '';
    returnStatus.value = '';
    applyEmpCode.value = '';
    startTime.value = '';
    endTime.value = '';
    handleSearch();
  }
  // 一键提交
  async function submit() {
    if (
      !booleanStore.partReturnList[0] ||
      booleanStore.partReturnList[0].value.length === 0
    ) {
      Notification.warning({
        title: '提示',
        content: '请至少选择一条数据',
        closable: true,
      });
      return;
    }

    // 计算已选择的表格数据
    const selectedTableData = computed(() => {
      return newData.value.responseBody?.result?.filter((item: any) =>
        booleanStore.partReturnList[0].value.includes(item.wmsReturnApplyId)
      );
    });
    const tabArray: any = [];
    selectedTableData.value.forEach((item: any) => {
      tabArray.push({
        wmsReturnApplyId: item.wmsReturnApplyId,
        returnStatus: item.returnStatus,
      });
    });

    const info: any = {
      data: tabArray,
    };
    const data = await submitReturnSales(info);
    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: data.message,
        closable: true,
      });
    } else {
      Notification.error({
        title: '失败',
        content: data.message,
        closable: true,
      });
    }
    handleSearch();
    // 清空数据
    booleanStore.toggleBool4(1);
  }

  // 一键删除
  async function onDel() {
    if (
      !booleanStore.partReturnList[0] ||
      booleanStore.partReturnList[0].value.length === 0
    ) {
      Notification.warning({
        title: '提示',
        content: '请至少选择一条数据',
        closable: true,
      });
      return;
    }

    // 计算已选择的表格数据
    const selectedTableData = computed(() => {
      return newData.value.responseBody?.result?.filter((item: any) =>
        booleanStore.partReturnList[0].value.includes(item.wmsReturnApplyId)
      );
    });
    const tabArray: any = [];
    selectedTableData.value.forEach((item: any) => {
      tabArray.push({
        wmsReturnApplyId: item.wmsReturnApplyId,
        returnStatus: item.returnStatus,
      });
    });

    const info: any = {
      data: tabArray,
    };
    const data = await deleteReturnApplyByIds(info);
    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: data.message,
        closable: true,
      });
    } else {
      Notification.error({
        title: '失败',
        content: data.message,
        closable: true,
      });
    }
    handleSearch();
    // 清空选择的数据
    booleanStore.toggleBool4(1);
  }
  // 缓存箱扫码
  async function prtHcxScan() {
    if (booleanStore.partList[0]?.value.length !== 1) {
      Notification.warning({
        title: '提示',
        content: '请选择一条数据',
        closable: true,
      });
    } else {
      const dataInfo: any = newData.value.responseBody?.result.filter(
        (item: any) =>
          item.wmsReturnApplyId === booleanStore.partList[0].value[0]
      );
      wmsDeliveryPlanId.value = dataInfo[0].wmsDeliveryPlanId;

      const info = ref({
        workbinCode: scanCode.value,
        wmsDeliveryPlanId: wmsDeliveryPlanId.value,
      });
      const data = await prtFrtHcxScan(info.value);
      if (data.retCode === '200') {
        materialCard.value = true;
        materialList.value = data.responseBody;
        Notification.success({
          title: '成功',
          content: '缓存箱扫码成功',
          closable: true,
        });
      } else {
        Notification.error({
          title: '失败',
          content: '缓存箱扫码失败',
          closable: true,
        });
      }
    }
  }

  // 物料出库
  async function prtMaterialOut() {
    const info = ref<any[]>([]);
    materialList.value.forEach((value: any) => {
      info.value.push({
        itemCode: value.itemCode,
        qualityCode: value.qualityCode,
        returnQty: value.wmsReturnApplyDTOList[0].returnQty,
        returnStatus: value.wmsReturnApplyDTOList[0].returnStatus,
        wmsDeliveryPlanId: wmsDeliveryPlanId.value,
        wmsReturnApplyId: booleanStore.partList[0].value[0],
        workbinCode: value.workbinCode,
      });
    });
    const dataInfo = ref({
      data: info.value,
    });
    booleanStore.toggleBool(0);
    try {
      const data = await prMaterialOut(dataInfo.value);
      if (data.retCode === '200' || data.retCode === '202') {
        booleanStore.toggleBool(0);
        materialList.value = [];
        materialCard.value = false;
        Notification.success({
          title: '成功',
          content: data.message,
          closable: true,
        });
      } else {
        booleanStore.toggleBool(0);
        materialList.value = [];
        materialCard.value = false;
        Notification.error({
          title: '失败',
          content: data.message,
          closable: true,
        });
      }
    } catch (error) {
      booleanStore.toggleBool(0);
      Notification.error({
        title: '失败',
        content: '网络异常',
        closable: true,
      });
    }
  }

  // 扫码操作
  async function scanSubmit() {
    if (scanCode.value === '9001') {
      // 缓存箱出库
      Notification.warning({
        title: '提示',
        content: '缓存箱已出库',
        closable: true,
      });
      scanCode.value = '';
      nextTick(() => {
        scanInput.value.focus();
      });
    } else if (scanCode.value.length === 12) {
      if (prtCode.value === '') {
        // 缓存箱扫码
        prtHcxScan();
        scanCode.value = '';
        nextTick(() => {
          scanInput.value.focus();
        });
      } else {
        Notification.warning({
          title: '提示',
          content: '已扫描一个缓存箱，请完成后续流程或者刷新页面',
          closable: true,
        });
      }
    } else if (scanCode.value === '9002') {
      // 缓存箱回库
      Notification.success({
        title: '成功',
        content: '缓存箱已回库',
        closable: true,
      });
      scanCode.value = '';
      nextTick(() => {
        scanInput.value.focus();
      });
    } else if (scanCode.value === '9005') {
      // 缓存箱出库
      prtMaterialOut();
      setTimeout(() => {
        handleSearch();
        booleanStore.toggleBool4(1);
      }, 2000);
      scanCode.value = '';
      nextTick(() => {
        scanInput.value.focus();
      });
    } else {
      const exists = materialList.value.some(
        (item: any) => item.wmsDeliverPlanDTOList[0].barcode === scanCode.value
      );
      if (exists) {
        Notification.success({
          title: '成功',
          content: '物料已经确认',
          closable: true,
        });
      } else {
        Notification.error({
          title: '失败',
          content: '扫描错误条码',
          closable: true,
        });
      }
      scanCode.value = '';
      nextTick(() => {
        scanInput.value.focus();
      });
    }
  }

  onMounted(() => {
    nextTick(() => {
      scanInput.value.focus();
    });
    handleSearch();
  });
  // 监听分页
  watch([() => booleanStore.pageNum, () => booleanStore.pageSize], () => {
    if (booleanStore.num5 === 10) {
      pageNumber.value = booleanStore.pageNum;
      pageSize.value = booleanStore.pageSize;
      handleSearch();
    }
  });
  watch(
    () => booleanStore.update,
    () => {
      if (booleanStore.num6 === 5) handleSearch();
    }
  );
</script>

<template>
  <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
    <a-col :span="6">
      <div>
        <a-input v-model="itemCode" placeholder="图号" size="large" />
      </div>
    </a-col>
    <a-col :span="6">
      <div>
        <a-input v-model="productCode" placeholder="机型" size="large" />
      </div>
    </a-col>
    <a-col :span="6">
      <div>
        <a-input v-model="batchNo" placeholder="批次" size="large" />
      </div>
    </a-col>
    <a-col :span="6">
      <div>
        <a-input v-model="startLotNo" placeholder="起始架次" size="large" />
      </div>
    </a-col>
  </a-row>

  <a-row class="row-top" :gutter="{ md: 8, lg: 24, xl: 32 }">
    <a-col :span="6">
      <div>
        <a-input v-model="endLotNo" placeholder="截止架次" size="large" />
      </div>
    </a-col>
    <a-col :span="6">
      <div>
        <a-input v-model="qualityCode" placeholder="质量编号" size="large" />
      </div>
    </a-col>
    <a-col :span="6">
      <div>
        <a-select v-model="returnStatus" placeholder=" 退库状态" size="large">
          <a-option label="编辑中" value="1"></a-option>
          <a-option label="待接收" value="2"></a-option>
          <a-option label="待确定" value="3"></a-option>
          <a-option label="保管待接收" value="4"></a-option>
          <a-option label="已驳回" value="5"></a-option>
          <a-option label="结束" value="6"></a-option>
          <a-option label="删除" value="7"></a-option>
        </a-select>
      </div>
    </a-col>
    <a-col :span="6">
      <div>
        <a-input v-model="applyEmpCode" placeholder="申请人" size="large" />
      </div>
    </a-col>
  </a-row>

  <a-row class="row-top" :gutter="{ md: 8, lg: 24, xl: 32 }">
    <a-col :span="6">
      <div>
        <a-date-picker
          v-model="startTime"
          style="width: 100%"
          placeholder="申请日期"
          size="large"
        />
      </div>
    </a-col>
    <a-col :span="6">
      <div>
        <a-date-picker
          v-model="endTime"
          style="width: 100%"
          placeholder="结束日期"
          size="large"
        />
      </div>
    </a-col>
  </a-row>
  <div class="flex-div">
    <a-button type="primary" size="large" @click="handleSearch">查询</a-button>
    <a-button class="btn-group" size="large" @click="reset">重置</a-button>
    <a-button
      class="btn-group"
      type="primary"
      size="large"
      @click="booleanStore.toggleBool(2)"
      >零件所在单位发起</a-button
    >
    <a-button type="primary" class="btn-reset" size="large" @click="submit"
      >提交</a-button
    >
    <a-button type="primary" class="btn-reset" size="large" @click="onDel"
      >删除</a-button
    >
    <!-- <a-button class="btn-group" type="primary" size="large"
      >缓存箱出库</a-button
    >
    <a-button type="primary" class="btn-group" size="large"
      >缓存箱扫码</a-button
    >
    <a-button type="primary" class="btn-group" size="large">物料出库</a-button>

    <a-button type="primary" class="btn-group" size="large"
      >缓存箱回库</a-button
    > -->
    <div class="btn-group">
      <a-input
        ref="scanInput"
        v-model="scanCode"
        placeholder="输入条码"
        size="large"
        @keyup.enter="scanSubmit"
      />
    </div>
  </div>
  <a-card v-show="materialCard">
    <a-row :gutter="{ md: 8, lg: 24, xl: 32 }">
      <a-col v-for="(value, index) in materialList" :key="index" :span="6">
        <a-card :style="{ width: '360px' }" title="缓存箱物料信息">
          <a-list size="small" :split="false">
            <a-list-item>缓存箱编码： {{ value.workbinCode }}</a-list-item>
            <a-list-item
              >物料条码：{{
                value.wmsDeliverPlanDTOList[0].barcode
              }}</a-list-item
            >
            <a-list-item> 图号：{{ value.itemCode }}</a-list-item>
            <a-list-item
              >名称：{{ value.mdsItemDTOList[0].itemName }}</a-list-item
            >
            <a-list-item
              >数量：{{ value.mdsItemDTOList[0].drawNo }}</a-list-item
            >
            <a-list-item class="nowrap"
              >退货数量：
              <a-input
                v-model="value.wmsReturnApplyDTOList[0].returnQty"
                class="input-class"
              />
            </a-list-item>
          </a-list>
        </a-card>
      </a-col>
    </a-row>
  </a-card>
</template>

<style scoped>
  .btn-group {
    margin-left: 10px;
  }

  .btn-reset {
    margin-left: 10px;
  }
  .row-top {
    margin-top: 10px;
  }
  .flex-div {
    margin-top: 20px;
    display: flex;
    justify-content: start;
  }

  .nowrap {
    white-space: nowrap;
  }
  .input-class {
    width: 80%;
  }
</style>
